package com.tianye.salon.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


public class FileUpload {
	public static void uploadFile(MultipartFile file, String fileSavePath) throws IOException {

	}

	// 上传图片（包含多张图片）统一处理方法
	public static List<Map<String, Object>> uploadFileAny(HttpServletRequest request, String images_upload_path)
			throws IOException {
		MultipartHttpServletRequest multipartRequest = null;
		List<Map<String, Object>> fileNames = new ArrayList<>();
		if (request instanceof MultipartHttpServletRequest) {
			multipartRequest = (MultipartHttpServletRequest) request;
		}
		if (CheckUtil.isEmpty(images_upload_path)) {
			images_upload_path = ProfileUtil.getInstance().read("prop.properties", "images_upload_path");
		}
		if (null != multipartRequest) {
			MultiValueMap<String, MultipartFile> values = multipartRequest.getMultiFileMap();
			Set<String> keys = values.keySet();// 遍历文件
			for (String key : keys) {
				List<MultipartFile> mutiFiles = values.get(key);
				for (MultipartFile imgFile : mutiFiles) {
					if (null != imgFile && !imgFile.isEmpty()) {
						Map<String, Object> map = new HashMap<>();
						// 保存原文件
						Map<String, Object> fileNameMap = saveNormalFileSimple(imgFile,
								request.getSession().getServletContext(), images_upload_path);
						//这里是调用原来的上传方法，跟admin一样，上面是文件系统用的
/*						Map<String, Object> fileNameMap = saveNormalFile(imgFile,
								request.getSession().getServletContext(), images_upload_path);
*/						map.put("filename", (String) fileNameMap.get("filename"));
						map.put("orginFilename", String.valueOf(fileNameMap.get("orginFilename")));// 返回上传文件的原文件名
						map.put("imgFile", imgFile);
						if (!fileNames.contains(map)) {
							fileNames.add(map);
						}
					}
				}
			}
			// 有存在一个filename多个file的情况
			/*
			 * Iterator<String> it = multipartRequest.getFileNames(); //
			 * 返回上传文件列表，map中存大图跟小图路径 while (it.hasNext()) { String fileName =
			 * it.next(); if (null != fileName && !"".equals(fileName)) { //
			 * 存储图片路径 // 获得第1张图片（根据前台的name名称得到上传的文件） MultipartFile imgFile =
			 * multipartRequest.getFile(fileName); if (null != imgFile &&
			 * !imgFile.isEmpty()) { //保存原图 Map<String, Object> fileNameMap =
			 * saveNormalFile(imgFile, request.getSession().getServletContext(),
			 * images_upload_path); //缩略图 String filename =
			 * resizeimage((File)fileNameMap.get("file"),
			 * request.getSession().getServletContext(), images_upload_path,
			 * null, null); Map<String, String> map = new HashMap<>();
			 * map.put("filename", (String) fileNameMap.get("filename"));
			 * map.put("small", filename); if (!fileNames.contains(map)) {
			 * fileNames.add(map); } } } }
			 */
		}
		return fileNames;
	}

	
	
	private static Map<String, Object> saveNormalFileSimple(MultipartFile file, ServletContext ctx, String file_upload_path) {
		Map map = new HashMap();
		// 得到文件原始名称
		String origName = file.getOriginalFilename();
		// 得到文件后缀名
		String ext = FilenameUtils.getExtension(origName).toLowerCase(Locale.ENGLISH);
		// 获取文件上传路径
		String file_path_Prefix = ProfileUtil.getInstance().read("prop.properties", "file_path_Prefix");
		try {
			// 原文件名
			map.put("orginFilename", origName);
			//区分项目图片logo
			if(file_upload_path.indexOf("\\/") < 0){
				file_upload_path = "/" + file_upload_path;
			}
			String filename = UploadUtils.generateFilename(file_upload_path, ext);
			// 保存文件名，用于存储
			map.put("filename", filename);
			ProfileUtil profileUtil = ProfileUtil.getInstance();
			String sysPath = profileUtil.read("file_store.properties", "filesystem.dir");
			String fileSavePath = sysPath+file_upload_path;
			File pathFile = new File(fileSavePath);
			if (!pathFile.exists() && !pathFile.isDirectory()) {
				pathFile.mkdirs();
			}
			String realpath = fileSavePath + "/"+origName;
			File destFile = new File(realpath);
			destFile.delete();
			destFile = UploadUtils.getUniqueFile(destFile);
			store(file, destFile);
			map.put("file", destFile);
			map.put("realpath", realpath);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 上传原始文件
	 * 
	 * @param file
	 * @param ctx
	 * @param file_upload_path
	 * @return
	 * @throws BusinessException
	 */
	public static Map saveNormalFile(MultipartFile file, ServletContext ctx, String file_upload_path){
		Map map = new HashMap();
		// 得到文件原始名称
		String origName = file.getOriginalFilename();
		// 得到文件后缀名
		String ext = FilenameUtils.getExtension(origName).toLowerCase(Locale.ENGLISH);
		// 获取文件上传路径
		String file_path_Prefix = ProfileUtil.getInstance().read("prop.properties", "file_path_Prefix");
		try {
			// 原文件名
			map.put("orginFilename", origName);
			//区分项目图片logo
			if(file_upload_path.indexOf("\\/") < 0){
				file_upload_path = "/" + file_upload_path;
			}
			String filename = UploadUtils.generateFilename(file_upload_path, ext);
			// 保存文件名，用于存储
			map.put("filename", filename);
			String realpath = "";
			// 如果配有Prefix目录，以此为准，否则保存到tomcat webapp 项目根目录下
			if (file_path_Prefix != null && file_path_Prefix.length() > 0) {
				realpath = file_path_Prefix + filename;
			} else {
				realpath = ctx.getRealPath(filename);
				if (realpath == null) {
					realpath = ctx.getRealPath("/") + filename;
				}
			}
			File destFile = new File(realpath);
			destFile = UploadUtils.getUniqueFile(destFile);
			store(file, destFile);
			map.put("file", destFile);
			map.put("realpath", realpath);
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 上传文件公共方法
	 * 
	 * @param file
	 * @param dest
	 * @throws IOException
	 */
	public static void store(MultipartFile file, File dest) throws IOException {
		try {
			UploadUtils.checkDirAndCreate(dest.getParentFile());
			file.transferTo(dest);
		} catch (IOException e) {
			throw e;
		}
	}
	
	
}
